///| 摄像头捕获模块
/// 负责摄像头的初始化、视频捕获和录制功能

import python
from utils import { Point, Rectangle, FaceDetectionError, Result }

/// 摄像头配置
pub struct CameraConfig {
  pub width : Int
  pub height : Int
  pub fps : Int
  pub device_id : Int
}

/// 视频录制器配置
pub struct VideoWriterConfig {
  pub filename : String
  pub fourcc : String
  pub fps : Double
  pub width : Int
  pub height : Int
}

/// 摄像头捕获器
pub struct CameraCapture {
  cap : python.PyObject
  writer : python.PyObject?
  config : CameraConfig
}

/// 默认摄像头配置
pub fn CameraConfig::default() -> CameraConfig {
  {
    width: 1280,
    height: 720,
    fps: 30,
    device_id: 0
  }
}

/// 初始化摄像头
pub fn CameraCapture::new(config : CameraConfig) -> Result[CameraCapture] {
  try {
    let cv2 = python.import("cv2")
    let cap = cv2.VideoCapture(config.device_id)
    
    // 设置摄像头分辨率
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, config.width)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, config.height)
    cap.set(cv2.CAP_PROP_FPS, config.fps)
    
    // 检查摄像头是否成功打开
    if not cap.isOpened() {
      return Err(CameraError("Failed to open camera"))
    }
    
    Ok({ cap, writer: None, config })
  } catch e {
    Err(CameraError("Camera initialization failed: " + e.to_string()))
  }
}

/// 初始化视频录制器
pub fn CameraCapture::init_writer(self : CameraCapture, writer_config : VideoWriterConfig) -> Result[CameraCapture] {
  try {
    let cv2 = python.import("cv2")
    let fourcc = cv2.VideoWriter_fourcc(*writer_config.fourcc)
    let writer = cv2.VideoWriter(
      writer_config.filename,
      fourcc,
      writer_config.fps,
      (writer_config.width, writer_config.height)
    )
    
    Ok({ ..self, writer: Some(writer) })
  } catch e {
    Err(IOError("Failed to initialize video writer: " + e.to_string()))
  }
}

/// 读取一帧图像
pub fn CameraCapture::read_frame(self : CameraCapture) -> Result[(Bool, python.PyObject)] {
  try {
    let (ret, frame) = self.cap.read()
    Ok((ret, frame))
  } catch e {
    Err(CameraError("Failed to read frame: " + e.to_string()))
  }
}

/// 写入一帧到视频文件
pub fn CameraCapture::write_frame(self : CameraCapture, frame : python.PyObject) -> Result[Unit] {
  match self.writer {
    Some(writer) => {
      try {
        writer.write(frame)
        Ok(())
      } catch e {
        Err(IOError("Failed to write frame: " + e.to_string()))
      }
    }
    None => Err(IOError("Video writer not initialized"))
  }
}

/// 释放资源
pub fn CameraCapture::release(self : CameraCapture) -> Unit {
  self.cap.release()
  match self.writer {
    Some(writer) => writer.release()
    None => ()
  }
}